package utilities;

import java.util.ArrayList;

import com.jme3.math.Vector2f;

/*
 * 
 */
public final class PointInPoly {
	
	public static boolean checkPoint(ArrayList<Vector2f> verts, double x, double y) {
		
		Vector2f currVert;
		Vector2f nextVert;
		double xc, yc, xn, yn;
		double slope, yintercept, xintercept;
		int numCross = 0;
		for (int i = 0; i < verts.size()-1; i++) {
			currVert = verts.get(i);			
			xc = currVert.x-x; //subtract off the test point, to center vertices at (0,0)
			yc = currVert.y-y;
			
			//System.out.println("XC,YC= " + xc + " " + yc);
			
			nextVert = verts.get(i+1);
			xn = nextVert.x-x;
			yn = nextVert.y-y;
			
			//System.out.println("XN,YN= " + xn + " " + yn);
			
			if ( //sign change in y coord
					(yc!=0 && yn!=0) && (((yc >= 0) && (yn <= 0)) || ((yc <= 0) && (yn >= 0)))
				) {
				//System.out.println("Y Sign change");
				
				if ((xc >= 0) && (xn >= 0)) { //both x coords positive
					numCross++; 
					//System.out.println("Both x Pos");
				}
				else if (((xc >= 0) && (xn <= 0)) || ((xc <= 0) && (xn >= 0))) { //sign change in x coords
					//compute x intersection
					slope = (yn-yc)/(xn-xc);
					yintercept = yc-slope*xc;
					xintercept = -yintercept/slope;
					//System.out.println("Slope=" + slope);
					//System.out.println("Yint=" + yintercept);
					//System.out.println("Xint= " + xintercept);
					if (xintercept >= 0) {
						numCross++;
					}
				}
			}
		}
		//System.out.println("NumCross= " + numCross);
		if (numCross%2 == 0) {			
			return false;
		}
		else
			return true;
	}

}
